package titan.data.components;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import titan.messages.Messages;

/**
 * Class to load a list of components from the repository path
 */
public class ComponentList {
	private ArrayList<ComponentData> compData;
	private int maxEngines;

	/**
	 * Read and instantiate component list by listing the repository path given
	 * @param reposPath - the repository path
	 * @throws Exception if there was an error while instantiating the component list
	 * @see ComponentData#ComponentData(File)
	 */
	public ComponentList(String reposPath) throws Exception{
		if(!reposPath.endsWith(File.separator))
			reposPath += File.separator;
		String componentPath = reposPath + "component" + File.separator; //$NON-NLS-1$
		File componentFile = new File(componentPath);
		if(!componentFile.exists())
			throw new Exception(Messages.CompFolderNFound+componentFile.getAbsolutePath());
		File[] componentList = componentFile.listFiles();
		Arrays.sort(componentList, new Comparator<File>() { 
			public int compare(File file1, File file2) {
				return file1.compareTo(file2);
			}
		});
		compData = new ArrayList<ComponentData>();
		maxEngines = 0;
		for(int i = 0; i < componentList.length; i++){
			if(componentList[i].isDirectory() && !componentList[i].isHidden()
					&& componentList[i].getName().compareTo(".svn") != 0){ //$NON-NLS-1$
				ComponentData cd = new ComponentData(componentList[i]);
				compData.add(cd);
				int index = compData.indexOf(cd);
				if(compData.get(index).getEnginesNumber() > maxEngines)
					maxEngines = compData.get(index).getEnginesNumber();
			}
		}
	}

	/**
	 * Get bigger number of engines at this component list
	 * @return maximum number of engines
	 */
	public int getMaxEngines(){
		return maxEngines;
	}

	/**
	 * Get component i
	 * @param i component index
	 * @return the component
	 */
	public ComponentData getComponent(int i){
		return compData.get(i);
	}

	/**
	 * Get size of this component list
	 * @return size of this component list
	 */
	public int getSize() {
		return compData.size();
	}
}